package com.dongdongshop.controller;

import com.dongdongshop.pojo.TbAdmin;
import com.dongdongshop.service.AdminService;
import com.dongdongsop.data.AjaxResult;
import com.dongdongsop.em.ResultEnum;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping("admin")
public class AdminController {

    @DubboReference
    private AdminService adminService;

    @RequestMapping("toLogin")
    public String toLogin(){
        return "login";
    }

    @RequestMapping("login")
    @ResponseBody
    public AjaxResult login(TbAdmin admin){
        try {
            Subject subject = SecurityUtils.getSubject();
            UsernamePasswordToken token = new UsernamePasswordToken(admin.getAdminName(),admin.getAdminPassword());
            try {
                subject.login(token);
            }catch (UnknownAccountException uae){
                return AjaxResult.R(ResultEnum.LOGIN_ERROR);
            }catch (IncorrectCredentialsException ice){
                ice.printStackTrace();
                return AjaxResult.R(ResultEnum.LOGIN_ERROR);
            }
            return AjaxResult.OK();
        }catch (Exception e){
            return AjaxResult.ERROR();
        }
    }

    @RequestMapping("toIndex")
    public String toIndex(){
        return "admin/index";
    }
}
